package com.guigu.controller;

import com.guigu.dto.loginDTO;
import com.guigu.entity.Login;
import com.guigu.exception.SsmException;
import com.guigu.service.LoginService;
import com.guigu.vo.Result;
import com.guigu.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@RestController
@RequestMapping("/Login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    @ResponseBody
    public Result queryByLogin(@RequestBody Login login){
        String password = this.loginService.queryByLogin(login);
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] dataBytes = login.getPassword().getBytes();
            digest.update(dataBytes);
            byte[] hashByte = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for(byte b : hashByte){
                String hex = Integer.toHexString(0xff & b);
                if(hex.length() == 1){
                    hexString.append('0');
                }
                hexString.append(hex);

            }
            System.err.println(hexString.toString());
            if(password.equals(hexString.toString())){
                return new Result<>("200","true","登录成功!",login.getUsername()+","+hexString.toString()+"loginyes");
            }else{
                return new Result("0","false","登录失败密码或账户有误!","");
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/getUserInfo/{username}")
    public Result getUserInfo(@PathVariable String username){
        String[] name = username.split(",");
        UserVO user = this.loginService.findUserByName(name[0]);
//        try {
//            getImage(user.getAvatar());
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        return new Result<>("200","true","获取用户信息成功!",user);
    }

    @RequestMapping("/SendingCode.action")
    public @ResponseBody String SendingCode(String email) {
        StringBuilder code = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        this.loginService.sendMail(email,""+code.toString(),"");

        return code.toString();
    }

    @PostMapping("/loginqd")
    public Result loginqd(@RequestBody loginDTO dto){
        try{
            Integer id=this.loginService.loginqd(dto);
            if(id!=null){
                return new Result<>("200", "true", "登录成功", null);
            }else{
                return new Result<>("400", "false", "登录失败", null);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new SsmException("异常");
        }
    }

//    public byte[] getImage(String imageUrl) throws IOException {
//            // 根据图片URL获取图片的二进制数据
//            byte[] imageBytes = getImageBytesFromUrl(imageUrl);
//            return imageBytes;
//    }
//
//    private byte[] getImageBytesFromUrl(String imageUrl) throws IOException {
//        URL url = new URL(imageUrl);
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        connection.setRequestMethod("GET");
//
//        // 如果有需要，可以设置请求头信息
//        // connection.setRequestProperty("Authorization", "Bearer token");
//
//        int responseCode = connection.getResponseCode();
//        if (responseCode == HttpURLConnection.HTTP_OK) {
//            InputStream inputStream = connection.getInputStream();
//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            byte[] buffer = new byte[1024];
//            int bytesRead;
//            while ((bytesRead = inputStream.read(buffer)) != -1) {
//                outputStream.write(buffer, 0, bytesRead);
//            }
//            inputStream.close();
//            outputStream.close();
//
//            return outputStream.toByteArray();
//        } else {
//            throw new IOException("获取图片URL失败: " + responseCode);
//        }
//    }
}
